package com.company.test32;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * Created by v on 16-12-8.
 */
public class Tick {
    private int tickCount;
    private int tickInterval;
    private int maxInterval;
    private int minInterval;

    private long step;
    private TickEvent e;
    private ArrayList<TickListener> tickListenerList;
    private Timer timer;

    public Tick(){
        this(100,5000,1,10);
    }

    public Tick(int tickInterval,int maxInterval,
                int minInterval,int step){
        this.step=step;
        this.minInterval=minInterval;
        this.maxInterval=maxInterval;
        this.tickInterval=tickInterval;
        tickCount=0;
        tickListenerList=new ArrayList<>();

        timer=new Timer(tickInterval, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //只有其在限定区间才会产生这种事件
                if(Tick.this.tickInterval>=Tick.this.minInterval
                        &&Tick.this.tickInterval<=Tick.this.maxInterval){
                    processEvent(new TickEvent(
                            Tick.this,tickCount,Tick.this.tickInterval));
                }else {
                    timer.stop();
                }
            }
        });
    }

    public void addTickListener(TickListener listener){
        if(!tickListenerList.contains(listener))
            tickListenerList.add(listener);
    }

    public void removeTickListener(TickListener listener){
        tickListenerList.remove(listener);
    }

    private void processEvent(TickEvent e){
        synchronized (this){
            tickInterval+=step;
            timer.setDelay(tickInterval);
            tickCount++;
        }

        for(int i=0;i<tickListenerList.size();i++){
            tickListenerList.get(i).handleTick(e);
        }
    }

    //开始Timer
    public void start(){
        timer.start();
    }

    //结束Timer
    public void stop(){
        timer.stop();
    }

    //构造器与访问器
    public int getMaxInterval() {
        return maxInterval;
    }

    public int getMinInterval() {
        return minInterval;
    }

    public int getTickCount() {
        return tickCount;
    }

    public int getTickInterval() {
        return tickInterval;
    }

    public long getStep() {
        return step;
    }

    public void setStep(long step) {
        this.step = step;
    }

    public void setTickInterval(int tickInterval) {
        this.tickInterval = tickInterval;
        timer.start();
    }

    public void setTickCount(int tickCount) {
        this.tickCount = tickCount;
    }

    public void setMinInterval(int minInterval) {
        this.minInterval = minInterval;
        timer.start();
    }

    public void setMaxInterval(int maxInterval) {
        this.maxInterval = maxInterval;
        timer.start();
    }
}
